\chapter{Introduction}
\label{sec:intro}

When a design progresses from simulation to hardware implementation, a user's
control and understanding of the system's current state drops dramatically.
To help bring up and debug low level software and hardware,
it is critical to have good debugging support built into the hardware.
When a robust OS is running on a core, software can handle many
debugging tasks. However, in many scenarios, hardware support is essential.

This document outlines a standard architecture for debug support
on RISC-V hardware platforms. This architecture allows a variety of implementations and
tradeoffs, which is complementary to the wide range of RISC-V implementations.
At the same time, this specification defines common interfaces to
allow debugging tools and components to target a variety of hardware
platforms based on the RISC-V ISA.

System designers may choose to add additional hardware debug support,
but this specification defines a standard interface for common
functionality.

\section{Terminology}

\begin{description}[style=nextline]
    \item[AMO]
        Atomic Memory Operation.
    \item[BYPASS]
        JTAG instruction that selects a single bit data register, also called BYPASS.
    \item[component]
        A RISC-V core, or other part of a hardware platform.
        Typically all components will be connected to a single system
        bus.
    \item[CSR]
        Control and Status Register.
    \item[DM]
        Debug Module (see Section \ref{dm}).
    \item[DMI]
        Debug Module Interface (see Section \ref{dmi}).
    \item[DR]
        JTAG Data Register.
    \item[DTM]
        Debug Transport Module (see Section \ref{dtm}).
    \item[DXLEN]
        Debug XLEN, which is the widest XLEN a hart supports, ignoring the
        current value of \Fmxl in \Rmisa.
    \item[GPR]
        General Purpose Register.
    \item[hardware platform]
        A single system consisting of one or more \emph{components}.
    \item[hart]
        A hardware thread in a RISC-V core.
    \item[IDCODE]
        32-bit Identification CODE, and a JTAG instruction that returns the IDCODE value.
    \item[IR]
        JTAG Instruction Register.
    \item[JTAG]
        Refers to work done by IEEE's Joint Test Action Group, described in
        IEEE 1149.1.
    \item[NAPOT]
        Naturally Aligned Powers-Of-Two.
    \item[NMI]
        Non-Maskable Interrupt.
    \item[physical address]
        An address that is directly usable on the system bus.
    \item[SBA]
        System Bus Access (see Section \ref{systembusaccess}).
    \item[TAP]
        Test Access Port, defined in IEEE 1149.1.
    \item[TM]
        Trigger Module (see Section \ref{sec:trigger}).
    \item[virtual address]
        An address as a hart sees it. If the hart is using address translation this
        may be different from the physical address. If there is no
        translation then it will be the same.
    \item[\Rxepc]
        The exception program counter CSR (e.g. \Rmepc) that is appropriate for
        the mode being trapped to.
\end{description}

\section{Context}

\begin{steps}{This document is written to work with:}
\item The RISC-V Instruction Set Manual, Volume I: User-Level ISA, Document
    Version 2.2 (the ISA Spec)
\item The RISC-V Instruction Set Manual, Volume II: Privileged Architecture,
    Version 1.12 (the Privileged Spec)
\end{steps}

\subsection{Versions}

Version 0.13 of this document was ratified by the RISC-V Foundation's board.
Versions 0.13.$x$ are bug fix releases to that ratified specification.

Version 0.14 was a working version that was never officially ratified.

Version 1.0.0 is almost entirely forwards and backwards compatible with Version 0.13.

\newcommand{\PR}[1]{\href{https://github.com/riscv/riscv-debug-spec/pull/#1}{\##1}}

\subsubsection{Bugfixes from 0.13 to 1.0}

\begin{steps}{Changes that fix a bug in the spec:}
    \item Fix order of operations described in \RdmSbdataZero. \PR{392}
    \item Resume ack is set after resume, in Section~\ref{runcontrol}. \PR{400}
    \item \FcsrTextraThirtytwoSselect applies to \FcsrTextraThirtytwoSvalue. \PR{402}
    \item \FcsrTcontrolMte only applies when action=0. \PR{411}
    \item \FacAccessmemoryAamsize does not affect Argument Width. \PR{420}
    \item Clarify that harts halt out of reset if \FdmDmcontrolHaltreq=1. \PR{419}
\end{steps}

\subsubsection{Incompatible Changes from 0.13 to 1.0}

\begin{steps}{Changes that are not backwards-compatible. Debuggers or
hardware implementations that implement 0.13 will have to change something in
order to implement 1.0:}
    \item Make haltsum0 optional if there is only one hart. \PR{505}
    \item System bus autoincrement only happens if an access actually
    takes place. (\RdmSbdataZero) \PR{507}
    \item Bump \FdmDmstatusVersion to 3. \PR{512}
    \item Require debugger to poll \FdmDmcontrolDmactive after lowering it. \PR{566}
    \item Add \FcsrIcountPending to \RcsrIcount. \PR{574}
\end{steps}

\subsubsection{Minor Changes from 0.13 to 1.0}

\begin{steps}{Changes that slightly modify defined behavior. Technically backwards
incompatible, but unlikely to be noticeable:}
    \item \FcsrDcsrStopcount only applies to hart-local counters. \PR{405}
    \item \FdmDmstatusVersion may be invalid when \FdmDmcontrolDmactive=0. \PR{414}
    \item Address triggers (\RcsrMcontrol) may fire on any accessed address. \PR{421}
    \item All trigger registers (Section~\ref{csrTrigger}) are optional. \PR{431}
    \item When extending IR, \RdtmBypass still is all ones. \PR{437}
    \item \FcsrDcsrEbreaks and \FcsrDcsrEbreaku are WARL. \PR{458}
    \item NMI are disabled by \FcsrDcsrStepie. \PR{465}
    \item R/W1C fields should be cleared by writing every bit high. \PR{472}
    \item Specify trigger priorities in Table~\ref{tab:priority} relative to exceptions. \PR{478}
    \item Time may pass before \FdmDmcontrolDmactive becomes high. \PR{500}
    \item Clear MPRV when resuming into lower privilege mode. \PR{503}
    \item Halt state may not be preserved across reset. \PR{504}
    \item Hardware should clear trigger action when \FcsrTdataOneDmode is
        cleared and action is 1. \PR{501}
    \item Change quick access exceptions to halt the target in
    Section~\ref{acQuickaccess}. \PR{585}
    \item Writing 0 to \RcsrTdataOne forces a state where \RcsrTdataTwo and
        \RcsrTdataThree are writable. \PR{598}
\end{steps}

\subsubsection{New Features from 0.13 to 1.0}

\begin{steps}{New backwards-compatible feature that did not exist before:}
    \item Add halt groups and external triggers in Section~\ref{hrgroups}. \PR{404}
    \item Reserve some DMI space for non-standard use. See \RdmCustom, and
        \RdmCustomZero through \RdmCustomFifteen. \PR{406}
    \item Reserve trigger \FcsrTdataOneType values for non-standard use. \PR{417}
    \item Add \FcsrEtriggerNmi bit to \RcsrEtrigger. \PR{408}
    \item Recommend matching on every accessed address. \PR{449}
    \item Add resume groups in Section~\ref{hrgroups}. \PR{506}
    \item Add \FdmAbstractcsRelaxedpriv. \PR{536}
    \item Move \RcsrScontext, renaming original to \RcsrMscontext, and create
        \RcsrHcontext. \PR{535}
    \item Add \RcsrMcontrolSix, deprecating \RcsrMcontrol. \PR{538}
    \item Add hypervisor support: \FcsrDcsrEbreakvs, \FcsrDcsrEbreakvu,
        \FcsrDcsrV, \RcsrHcontext, \RcsrMcontrol, \RcsrMcontrolSix, and
        \RvirtPriv. \PR{549}
    \item Optionally make \FdmDmstatusAnyunavail and \FdmDmstatusAllunavail
    sticky, controlled by \FdmDmstatusStickyunavail. \PR{520}
    \item Add \RcsrTmexttrigger to support trigger module external trigger
        inputs. \PR{543}
    \item Describe \RcsrMcontrol and \RcsrMcontrolSix behavior with atomic instructions. \PR{561}
    \item Trigger hit bits must be set on fire, may be set on match. \PR{593}
    \item Add \FcsrTextraThirtytwoSbytemask and \FcsrTextraSixtyfourSbytemask
        to \RcsrTextraThirtytwo and \RcsrTextraSixtyfour. \PR{588}
    \item Allow debugger to request harts stay alive with keepalive bit in
        Section~\ref{keepalive}. \PR{592}
    \item Add \FdmDmstatusNdmresetpending to allow a debugger to determine
        when ndmreset is complete. \PR{594}
    \item Add \FcsrTmexttriggerIntctl to support triggers from an interrupt controller. \PR{599}
\end{steps}
\section{About This Document}

\subsection{Structure}

This document contains two parts. The main part of the document is the
specification, which is given in the numbered chapters. The second part
of the document is a set of appendices. The information
in the appendices is intended to clarify and provide examples, but is
not part of the actual specification.

\subsection{ISA vs. non-ISA}

This specification consists of both ISA and non-ISA parts. ISA parts specify
hart state and behavior. Non-ISA parts specify non-hart state and behavior.
Chapters whose contents are solely one or the other are labeled as such in their
title. Chapters without such a label apply to both ISA and non-ISA

\subsection{Register Definition Format}

All register definitions in this document follow the format shown below.  A
simple graphic shows which fields are in the register. The upper and lower bit
indices are shown to the top left and top right of each field. The total number
of bits in the field are shown below it.

After the graphic follows a table which for each field lists its name,
description, allowed accesses, and reset value. The allowed accesses are listed
in Table~\ref{tab:access}. The reset value is either a constant or ``Preset.''
The latter means it is an implementation-specific legal value.

Names of registers and their fields are hyperlinks to their definition, and are
also listed in the index on page \pageref{index}.

\input{sample_registers.tex}

\begin{table}[htp]
    \centering
    \caption{Register Access Abbreviations}
    \label{tab:access}
    \begin{tabulary}{\textwidth}{|l|L|}
        \hline
        R & Read-only. \\
        \hline
        R/W & Read/Write. \\
        \hline
        R/W1C & Read/Write Ones to Clear. Writing 0 to every bit has no effect.
        Writing 1 to every bit clears the field. The result of other writes is
        undefined. \\
        \hline
        WARZ & Write any, read zero. A debugger may write any value. When read
        this field returns 0. \\
        \hline
        W1 & Write-only. Only writing 1 has an effect. When read the returned
        value should be 0. \\
        \hline
        WARL & Write any, read legal. A debugger may write any value. If a
        value is unsupported, the implementation converts the value to one that
        is supported. \\
        \hline
    \end{tabulary}
\end{table}

%\input{reading_order.tex}

\section{Background}

There are several use cases for dedicated debugging hardware, both
internal to a CPU core and with an external connection.
This specification addresses the use cases listed below. Implementations
can choose not to implement every feature, which means some use cases might
not be supported.

\begin{itemize}

\item Debugging low-level software in the absence of an OS or other software.

\item Debugging issues in the OS itself.

\item Bootstrapping a hardware platform to test, configure, and program components before
  there is any executable code path in the hardware platform.

\item Accessing hardware on a hardware platform without a working CPU.

\end{itemize}

In addition, even without a hardware debugging interface,
architectural support in a RISC-V CPU can aid software debugging and
performance analysis by allowing hardware triggers and breakpoints.

\section{Supported Features}

The debug interface described in this specification supports the following features:

\begin{enumerate}
   \item All hart registers (including CSRs) can be read/written.
   \item Memory can be accessed either from the hart's point of view, through
       the system bus directly, or both.
   \item RV32, RV64, and future RV128 are all supported.
   \item Any hart in the hardware platform can be independently debugged.
   \item A debugger can discover almost\footnote{Notable exceptions include
       information about the memory map and peripherals.} everything it needs
       to know itself, without user configuration.
   \item Each hart can be debugged from the very first instruction executed.
   \item A RISC-V hart can be halted when a software breakpoint instruction is
       executed.
   \item Hardware single-step can execute one instruction at a time.
   \item Debug functionality is independent of the debug transport used.
   \item The debugger does not need to know anything about the microarchitecture
       of the harts it is debugging.

   \item Arbitrary subsets of harts can be halted and resumed simultaneously.
       (Optional)
   \item Arbitrary instructions can be executed on
       a halted hart. That means no new debug functionality is needed when a
       core has additional or custom instructions or state, as
       long as there exist programs
       that can move that state into GPRs. (Optional)
   \item Registers can be accessed without halting. (Optional)
   \item A running hart can be directed to execute a short sequence
       of instructions, with little overhead. (Optional)
   \item A system bus master allows memory access without
       involving any hart. (Optional)
   \item A RISC-V hart can be halted when a trigger matches the PC,
       read/write address/data, or an instruction opcode. (Optional)
    \item Harts can be grouped, and harts in the same group will all halt when
        any of them halts. These groups can also react to or notify external
        triggers. (Optional)
\end{enumerate}

This document does not suggest a strategy or implementation for hardware test,
debugging or error detection techniques. Scan, built-in self test (BIST), etc. are out of scope of
this specification, but this specification does not intend to limit their use
in RISC-V systems.

It is possible to debug code that uses software threads, but there is no
special debug support for it.
